import { AxiosRequestConfig, AxiosResponse } from 'axios'
import loading from './loading'

function getToken(): any {}
export default {
  request: {
    onFulfilled(request: AxiosRequestConfig) {
      /**
       * 根据项目实际情况来对 config 做处理
       * 这里对 config 不做任何处理，直接返回
       */
      const token = getToken()
      // const url = request.url
      request.headers = {}
      if (token) {
        request.headers.Authorization = `${token}`
      }
      request.headers['gx-scene'] = 'firewall-access-relationship-activation'
      if ((<any>request).loading) {
        loading.start()
      }
      return request
    },
    onRejected(error: any): Promise<never> {
      return Promise.reject(error)
    },
  },
  // 响应拦截器
  response: {
    onFulfilled(response: AxiosResponse) {
      const { headers } = response
      const contentDes = headers['content-disposition']
      if ((<any>response).loading) {
        loading.end()
      }
      if (contentDes && contentDes.includes('attachment')) {
        return response
      }
      return response.data
    },
    async onRejected(error: any) {
      const { message, response } = error
      console.warn('[common-http:error]:', response)
      if (response && response.data) {
        let respData = response.data
        if (respData instanceof Blob) {
          respData = await blobToObject(respData)
        }
        const respDataCode = respData.code
        const respDataStatus = respData.status
        // 状态码为 -1200X的时候为Token失效 需要实现登出
        if (respDataCode > -12999 && respDataCode < -12000) {
          // antMessage.warning(`${respData.description || ''}`)
        } else if (respDataStatus) {
          // notification.error({
          //   message: respDataStatus,
          //   description: `[${respData.path}]: ${respData.error} `,
          // })
        } else {
        }
      } else if (message) {
      }
      return Promise.reject(error)
    },
  },
}
function blobToObject(blob: Blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (event: any) => {
      try {
        const object = JSON.parse(event.target.result)
        resolve(object)
      } catch (error) {
        reject(error)
      }
    }
    reader.onerror = (event: any) => {
      reject(event.target.error)
    }
    reader.readAsText(blob)
  })
}
